﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using Aandelendelen.Obs;

namespace Aandelendelen.Admin
{
	public partial class AdminSearchUser : AdminBaseForm
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			this.resultPanel.Visible = this.IsPostBack;
			this.entryPanel.Visible = !this.IsPostBack;

			if (this.IsPostBack)
				this.ShowResult();
		}

		private void ShowResult()
		{
			string uid = this.tbUserId.Text;
			string lastName = this.tbAchternaam.Text;
			string city = this.tbWoonplaats.Text;
			string email = this.tbEmail.Text;

			string filter = this.RadioButtonList1.SelectedValue;

			StringBuilder str = new StringBuilder("SELECT Naw.Id, Naw.Voorletters, Naw.Tussenvoegsel, Naw.Achternaam, Naw.Woonplaats, Naw.Geslacht, Naw.Email, Naw.Rekeningnummer, Naw.Gebruikersnaam, Naw.Aanmelddatum, Naw.Lastlogin, Sum(SaldoMutatie.Bedrag) AS Saldo");
			str.Append(" FROM Naw LEFT JOIN Saldomutatie ON Naw.[Id] = Saldomutatie.[NawId]");
			str.Append(" WHERE Naw.AanmeldDatum <> #01-01-1980# AND Naw.AfmeldDatum = #01-01-1980#");

			this.AddLike("Gebruikersnaam", uid, str);
			this.AddLike("Achternaam", lastName, str);
			this.AddLike("Woonplaats", city, str);
			this.AddLike("Email", email, str);

			str.Append(" GROUP BY Naw.Id, Naw.Voorletters, Naw.Tussenvoegsel, Naw.Achternaam, Naw.Woonplaats, Naw.Geslacht, Naw.Email, Naw.Rekeningnummer, Naw.Gebruikersnaam, Naw.Aanmelddatum, Naw.Lastlogin");

			if (filter == "1")
			{
				str.Append(" HAVING Sum(SaldoMutatie.Bedrag) > 0");
			}

			this.dsUser.SelectCommand = str.ToString();

			this.GridView1.DataBind();
		}

		private void AddLike(string column, string value, StringBuilder query)
		{
			if (!string.IsNullOrEmpty(value))
			{
				query.Append(" AND "); query.Append(column); query.Append(" LIKE '%"); query.Append(value); query.Append("%'");
			}
		}
	}
}